<?php

namespace server\dao;

use Yii;
use yii\mongodb\Query;

/**
 * This is the model class for collection "runtime".
 *
 * @property \MongoDB\BSON\ObjectID|string $_id
 * @property mixed $id
 * @property mixed $info
 */
class Runtime extends \common\core\server\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function collectionName()
    {
        return 'runtime';
    }

    /**
     * {@inheritdoc}
     */
    public function attributes()
    {
        return [
            '_id',
            'time',
            'info',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['time', 'info'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            '_id' => 'ID',
            'time' => 'Time',
            'info' => 'Info',
        ];
    }

    public function getRuntimeList($params, $isAll)
    {
        $query = new Query();
        $query->from('runtime');
        if ($this->issetAndEmpty($params, 'ip')) {
            $query->andWhere(['uuid' => $params['ip']]);
        }
        if ($this->issetAndEmpty($params, 'startTime')) {
            $query->andWhere(['>=', 'timestamp', (int)$params['startTime']]);
        }
        if ($this->issetAndEmpty($params, 'endTime')) {
            $query->andWhere(['<=', 'timestamp', (int)$params['endTime']]);
        }
        $query->orderBy('timestamp desc');
        $query->limit(15);
        //return $query->createCommand()->getRawSql();
        return $isAll ? $query->all() : $this->mongodbPage($query);
    }

    public function getLastRuntimeById($ip)
    {
        $query = new Query();
        $query->from('runtime');
        $query->where(['uuid' => $ip]);
        $query->orderBy(['timestamp' => SORT_DESC]);
        return $query->one();

    }


    public function getLastRuntimeGroupId($ips)
    {
        $q = new Query();
        $pipelines[] = ['$match' => ['uuid' => ['$in' => $ips]]];
        $pipelines[] = [
            '$group' => [
                '_id' => '$uuid',
                'uuid' => [
                    '$last' => '$uuid'
                ],
                'cpu' => [
                    '$last' => '$cpu'
                ],
                'ram' => [
                    '$last' => '$ram'
                ],
                'disk' => [
                    '$last' => '$disk'
                ],
                'net' => [
                    '$last' => '$net'
                ],
                'process' => [
                    '$last' => '$process'
                ],
                'timestamp' => [
                    '$last' => '$timestamp'
                ],

            ],
        ];
        $pipelines[] = ['$sort' => ['timestamp' => -1]];//1正序 -1倒序
        return $res = $q->from('runtime')->getCollection()->aggregate($pipelines);

    }


}
